package cn.edu.xjtu.剑指offer.buildTree;

import cn.edu.xjtu.Util.TreeNode.TreeNode;

/**
 * https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
 * 剑指 Offer 07. 重建二叉树
 * <p>
 * 输入某二叉树的前序遍历和中序遍历的结果，请构建该二叉树并返回其根节点。
 * <p>
 * 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) {
            return null;
        }
        return helpBuild(preorder, inorder, 0, inorder.length, 0, preorder.length);
    }

    private TreeNode helpBuild(int[] preorder, int[] inorder, int inStart, int inEnd, int preStart, int preEnd) {
        if (inStart == inEnd) {
            return null;
        }
        int rootVal = preorder[preStart];
        int rootIdx = 0;
        for (int i = inStart; i < inEnd; i++) {
            if (inorder[i] == rootVal) {
                rootIdx = i;
                break;
            }
        }
        TreeNode root = new TreeNode(rootVal);
        int leftLen = rootIdx - inStart;
        root.left = helpBuild(preorder, inorder, inStart, rootIdx, preStart + 1, preStart + leftLen + 1);
        root.right = helpBuild(preorder, inorder, rootIdx + 1, inEnd, preStart + leftLen + 1, preEnd);

        return root;
    }
}
